package com.zz.common.widget;

import com.zz.common.utils.ZLog;

import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class ZFixedGridView extends ViewGroup {

	private static final String TAG = "ZFixedGridView";
	
	private int mCellWidth;
	private int mCellHeight;
	
	private int mColNum;

	public ZFixedGridView(Context context) {
		super(context);
	}

	public ZFixedGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ZFixedGridView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void setColNom(int colNum) {
		if (colNum > 0) {
			mColNum = colNum;
		} else {
			throw new IllegalArgumentException("colNum must bigger than 0");
		}
	}

	public void setCellHeightByPixel(int pixels) {
		mCellHeight = pixels;
	}

	public void setCellHeightByDip(int dip) {
		DisplayMetrics dm = getResources().getDisplayMetrics();
		int heightPixels = (int) (dip * dm.density + 0.5);
		setCellHeightByPixel(heightPixels);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int cellWidthSpec = MeasureSpec.makeMeasureSpec(mCellWidth,
				MeasureSpec.AT_MOST);
		int cellHeightSpec = MeasureSpec.makeMeasureSpec(mCellHeight,
				MeasureSpec.AT_MOST);
		int count = getChildCount();
		for (int index = 0; index < count; index++) {
			final View child = getChildAt(index);
			child.measure(cellWidthSpec, cellHeightSpec);
		}
		// Use the size our parents gave us
		setMeasuredDimension(resolveSize(mCellWidth * count, widthMeasureSpec),
				resolveSize(mCellHeight * count, heightMeasureSpec));
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int cellWidth = mCellWidth;
		int cellHeight = mCellHeight;
		int columns = (r - l) / cellWidth;
		if (columns < 0) {
			columns = 1;
		}
		int x = 0;
		int y = 0;
		int i = 0;
		int count = getChildCount();
		for (int index = 0; index < count; index++) {
			final View child = getChildAt(index);
			int w = child.getMeasuredWidth();
			int h = child.getMeasuredHeight();
			int left = x + ((cellWidth - w) / 2);
			int top = y + ((cellHeight - h) / 2);
			child.layout(left, top, left + w, top + h);
			if (i >= (columns - 1)) {
				// advance to next row
				i = 0;
				x = 0;
				y += cellHeight;
			} else {
				i++;
				x += cellWidth;
			}
		}
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		ZLog.d(TAG, ZLog.LOG_LEVEL_DEBUG, "onSizeChanged");
		if(mColNum > 0) {
			mCellWidth = w/mColNum;
		} else {
			mCellWidth = w;
		}
	}
}
